using Models.Models;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using System.Security.Cryptography.X509Certificates;

namespace Services;

/// <summary>
/// 首页服务实现
/// </summary>
public class HomeService : IHomeService
{
  private readonly ShopxoContext _context;
  private readonly string _baseUrl = "https://shop.okbyby.com";

  public HomeService(ShopxoContext context)
  {
    _context = context;
  }

  /// <summary>
  /// 获取首页导航数据
  /// </summary>
  public async Task<IEnumerable<object>> GetNavigationAsync()
  {
    return await _context.SAppHomeNav
        .Where(x => x.Platform == "app" && x.IsEnable == 1)
        .OrderBy(x => x.Sort)
        .Select(x => new
        {
          id = x.Id.ToString(),
          name = x.Name,
          images_url = _baseUrl + x.ImagesUrl,
          event_value = x.EventValue,
          event_type = x.EventType,
          bg_color = x.BgColor,
          images_url_old = x.ImagesUrl
        })
        .ToListAsync();
  }

  public async Task<IEnumerable<object>> GetBannerListAsync()
  {
    return await _context.SSlide
      .Where(x => x.Platform == "app" && x.IsEnable == 1)
      .OrderBy(x => x.Sort)
      .Select(x => new
      {
        name = x.Name,
        images_url = _baseUrl + x.ImagesUrl,
        images_url_old = x.ImagesUrl,
        event_value = x.EventValue,
        event_type = x.EventType,
        bg_color = x.BgColor,
      }).ToListAsync();
  }

  /// <summary>
  /// 获取首页推荐商品
  /// </summary>
  public async Task<IEnumerable<object>> GetRecommendedGoodsAsync()
  {
    var goodsQuery = await _context.SGoods
        .Where(x => x.IsHomeRecommended == 1 && x.IsShelves == 1 && x.IsDeleteTime == 0)
        .OrderByDescending(x => x.Id)
        .Take(10)
        .ToListAsync();

    return goodsQuery.Select(x => new
    {
      id = x.Id.ToString(),
      brand_id = x.BrandId.ToString(),
      title = x.Title,
      title_color = x.TitleColor,
      model = x.Model,
      place_origin = x.PlaceOrigin.ToString(),
      inventory = x.Inventory.ToString(),
      inventory_unit = x.InventoryUnit,
      images = _baseUrl + x.Images,
      original_price = x.OriginalPrice,
      min_original_price = x.MinOriginalPrice.ToString("0.00"),
      max_original_price = x.MaxOriginalPrice.ToString("0.00"),
      price = x.Price,
      min_price = x.MinPrice.ToString("0.00"),
      max_price = x.MaxPrice.ToString("0.00"),
      give_integral = x.GiveIntegral.ToString(),
      buy_min_number = x.BuyMinNumber.ToString(),
      buy_max_number = x.BuyMaxNumber.ToString(),
      is_deduction_inventory = x.IsDeductionInventory.ToString(),
      is_shelves = x.IsShelves.ToString(),
      is_home_recommended = x.IsHomeRecommended.ToString(),
      is_activity = x.IsActivity.ToString(),
      is_spike = x.IsSpike.ToString(),
      content_web = x.ContentWeb,
      photo_count = x.PhotoCount.ToString(),
      sales_count = x.SalesCount.ToString(),
      access_count = x.AccessCount.ToString(),
      video = x.Video,
      home_recommended_images = _baseUrl + x.HomeRecommendedImages,
      is_delete_time = x.IsDeleteTime.ToString(),
      add_time = x.AddTime.ToString(),
      upd_time = x.UpdTime.ToString(),
      goods_url = _baseUrl + "/index.php?s=/index/goods/index/id/" + x.Id + ".html",
      images_old = x.Images,
      video_old = x.Video,
      home_recommended_images_old = x.HomeRecommendedImages,
      place_origin_name = "",
      brand_name = "",
      specifications = GetGoodsSpecifications(x.Id).Result,
      show_field_original_price_text = "原价",
      show_field_price_text = "销售价"
    });
  }

  /// <summary>
  /// 获取首页广告数据
  /// </summary>
  public List<object> GetAdvertisementsAsync()
  {
    return new List<object>
    {
      new
      {
        id = 1,
        name = "特价活动",
        images = "https://shop.okbyby.com/static/upload/images/slide/2021/02/09/1612830575297584.jpeg"
      }
    };
  }

  /// <summary>
  /// 获取热搜关键词
  /// </summary>
  public async Task<IEnumerable<string>> GetHotSearchKeywordsAsync()
  {
    return await _context.SSearchHistory
        .Where(x => x.Keywords != "")
        .GroupBy(x => x.Keywords)
        .OrderByDescending(g => g.Count())
        .Select(g => g.Key)
        .Take(10)
        .ToListAsync();
  }

  public async Task<IEnumerable<object>> GetGoodsSpecifications(uint goodsId)
  {
    return await _context.SGoodsSpecType
        .Where(x => x.GoodsId == goodsId)
        .Select(x => new
        {
          id = x.Id,
          goods_id = x.GoodsId,
          name = x.Name,
          value = JsonSerializer.Deserialize<List<object>>(x.Value ?? "[]", new JsonSerializerOptions()) ?? new List<object>(),
          add_time = x.AddTime.ToString()
        })
        .ToListAsync();
  }
}